package cn.uin.types.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Auther: uIn
 * @Date: 2025/10/19 - 10 - 19 - 14:37
 * @Description: Jwt工具类
 * @version: 1.0
 */
public class JwtUtils {
    // 秘钥
    private final static String SECRET = "HSyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9";

    private final static String ISS = "uIn";

    private final static String ROLES = "roles";

    private final static String MENUS = "menus";

    /**
     * 创建一个token
     *
     * @param username
     * @return
     */
    public static String generateToken(String username, Map<String, Object> claims) {
        return Jwts.builder()
                // 这里要先set claims，放到后面会覆盖别的字段
                .setClaims(claims)
                .setIssuer(ISS)
                .setSubject(username)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    /**
     * 解析token
     */
    public static Claims getClaimsByToken(String token) {
        try {
            return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            System.out.println("validate is token error");
            return null;
        }
    }

    /**
     * 从token中获取用户名
     *
     * @param token
     * @return
     */
    public static String getUsername(String token) {
        return getClaimsByToken(token).getSubject();
    }

    /**
     * 从token中获取roles
     *
     * @param token
     * @return
     */
    public static List<String> getUserRoles(String token) {
        return (List<String>) getClaimsByToken(token).get(ROLES);
    }

    /**
     * 从token中获取menus
     *
     * @param token
     * @return
     */
    public static List<String> getUserMenus(String token) {
        return (List<String>) getClaimsByToken(token).get(MENUS);
    }

    /**
     * 判断 token 是否过期
     */
    public static boolean isTokenExpired(Date expiration){
        return expiration.before(new Date());
    }

}
